# coding=utf-8
import json
import logging

from django.views.decorators.http import require_POST

from api.transaction import handler as transaction_handler
from common.account.db.account import get_account
from common.utils import exceptions as err
from common.utils.api import (token_required)
from common.utils.decorator import response_wrapper
from common.pay.model import PAY_STATUS, CREATED_BY_TYPE

_LOGGER = logging.getLogger(__name__)


@require_POST
@response_wrapper
@token_required
def create_pay_submit(req):
    try:
        param_dct = json.loads(req.body)
        pay_type = int(param_dct.get('type'))
        user_id = int(param_dct.get('user_id'))
        pay_amount = float(param_dct['pay_amount'])  # 充值金额
        content = param_dct['content']
        sdk_version = param_dct.get('sdk_version')
        channel_id = param_dct.get('channel_id') and int(param_dct.get('channel_id'))
        user = get_account(user_id)
    except:
        raise err.ParamError(u'参数错误')
    if not user:
        raise err.ParamError(u'用户不存在')
    pay_id = transaction_handler.create_pay_id(user_id, pay_type, created_by=CREATED_BY_TYPE.CONSOLE)

    pay_data = transaction_handler.submit_pay(
        user, pay_id, pay_amount, content, sdk_version, channel_id)

    _LOGGER.info("create_pay_submit ,console user {} : {}".format(req.user_id, param_dct))
    return dict(charge=pay_data)
